/**
 * User: yeqingzhou01
 * Date: 14-4-23
 * Time: 下午9:32
 */
var WebSocketServer = require('websocket').server;
var WebSocket = require('faye-websocket');
var http = require('http');

exports.WsServer = function (httpServer, onOpen, onReceived) {
    var _this = this;
    _this.httpServer = httpServer;
    _this.clients = [];

    _this.httpServer.on('upgrade', function(request, socket, body) {
        if (WebSocket.isWebSocket(request)) {
            var ws = new WebSocket(request, socket, body);
            var index = _this.clients.push(ws) - 1;

            ws.on('open', function(event){
                onOpen(ws, event);
            });

            ws.on('message', function(event) {
                console.log('WS received msg: ' + event.data);
                onReceived(event.data);
            });

            ws.on('close', function(event) {
                console.log('close', event.code, event.reason);
                _this.clients.splice(index, 1);
                ws = null;
            });
        }
    });
    _this.broadcast = function (obj) {
        for(var i = 0; i < _this.clients.length; i++){
            _this.clients[i].send(JSON.stringify(obj));
        }
    }
}
